import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

public class UtilRMS {

	private static RecordStore rs = null;
	private static int variables = 1;

	public static final int RMS_RUTA_ACTUAL = variables++;
	public static final int RMS_FICHERO_ACTUAL = variables++;
	public static final int RMS_VOLUMEN_ACTUAL = variables++;
	public static final int RMS_DIRECTORIO_PLAY = variables++;
	public static final int RMS_REPRODUCE_CONTINUO = variables++;
	public static final int RMS_FICHERO_CARATULA = variables++;

	public static void openRecStore() {
		try {
			// RecordStore.deleteRecordStore(NOMBRE_RMS);
			
			// The second parameter indicates that the record store
			// should be created if it does not exist

			rs = RecordStore.openRecordStore(Constantes.NOMBRE_RMS, true);
			initRMS();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void closeRecStore() {
		try {
			rs.closeRecordStore();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void initRMS() {
		try {
			RecordEnumeration registros = rs
					.enumerateRecords(null, null, false);
			// Creamos las variables necesarias, si es que nos falta alguna
			for (int numReg = registros.numRecords() + 1; numReg < variables; numReg++) {
				rs.addRecord(null, 0, 0);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String getData(int id) {
		String salida = null;
		try {
			// Obtenemos el dato serializado del registro
			ByteArrayInputStream bais = new ByteArrayInputStream(rs
					.getRecord(id));
			DataInputStream is = new DataInputStream(bais);
			// Des-serializamos el registro
			salida = is.readUTF();
		} catch (Exception e) {
			//Si viene por aqui puede ser porque no haya nada en el registro numero "id"
			//e.printStackTrace();
		} 

		return salida;
	}

	public static void setData(int i, String dato) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream os = new DataOutputStream(baos);
		try {
			// Serializar el dato
			os.writeUTF(dato);
			byte[] b = baos.toByteArray();
			
			// setteamos el valor del registro
			rs.setRecord(i, b, 0, b.length);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
